package com.bishe.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bishe.entity.User;
import com.bishe.entity.resp.PageParam;
import com.bishe.entity.resp.R;
import com.bishe.exception.CommonException;
import com.bishe.service.UserService;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.List;

/**
 * (User)表控制层
 *
 * @author makejava
 * @since 2024-04-03 23:24:50
 */
@RestController
@RequestMapping("user")
@Api(tags = "用户信息控制器")
public class UserController {
    /**
     * 服务对象
     */
    @Resource
    private UserService userService;


    @GetMapping("myClass/{id}")
    public R myClass(@PathVariable String id){
        return R.data(this.userService.myClass(id));
    }

  /**
     * 分页查询所有数据
     *
     * @return 所有数据
     */
    @PostMapping("page")
    public R selectAll(@RequestBody PageParam pageParam) {
        return R.data(this.userService.page(pageParam));
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public R selectOne(@PathVariable Serializable id) {
        return R.data(this.userService.getById(id));
    }

    /**
     * 新增数据
     *
     * @param user 实体对象
     * @return 新增结果
     */
    @PostMapping
    public R insert(@RequestBody User user) {
        if ("admin".equals(user.getUsername())){
            throw new CommonException("admin用户名已存在");
        }
        User one = userService.getOne(Wrappers.lambdaQuery(User.class)
                .eq(User::getUsername, user.getUsername())
                .eq(User::getType, user.getType()));
        if (one !=null){
            throw new CommonException("用户名已存在");
        }

        return R.data(this.userService.save(user));
    }

    /**
     * 修改数据
     *
     * @param user 实体对象
     * @return 修改结果
     */
    @PutMapping
    public R update(@RequestBody User user) {
        return R.data(this.userService.updateById(user));
    }

    /**
     * 删除数据
     *
     * @param idList 主键结合
     * @return 删除结果
     */
    @DeleteMapping
    public R delete(@RequestParam("idList") List<Long> idList) {
        return R.data(this.userService.removeByIds(idList));
    }
}

